package com.thunder.rebot.rebotclient.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.limedia.explorer.centralcontrol.ControlActivity;
import com.thunder.rebot.rebotclient.R;
import com.thunder.rebot.rebotclient.activity.LoginActivity;
import com.thunder.rebot.rebotclient.application.RobotApplication;
import com.thunder.rebot.rebotclient.entity.Network;
import com.thunder.rebot.rebotclient.entity.PicRegistEntity;
import com.thunder.rebot.rebotclient.entity.QuerySQLEntity;
import com.thunder.rebot.rebotclient.utils.ClientUtils;
import com.thunder.rebot.rebotclient.utils.LogUtil;

import java.io.IOException;
import java.util.Arrays;

/**
 * Created by yuechunan on 18-7-17.
 */

public class ServiceClient extends Service {

    private static final String TAG = "ServiceClient";
    public static Client client;
    private SharedPreferences sharedPreferences;
    private byte[] oneByte;
    private Handler handler;
    private boolean connectFlag;

    /**
     * 绑定服务时才会调用
     * 必须要实现的方法
     *
     * @param intent
     * @return
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 首次创建服务时，系统将调用此方法来执行一次性设置程序（在调用 onStartCommand() 或 onBind() 之前）。
     * 如果服务已在运行，则不会调用此方法。该方法只被调用一次
     */
    @Override
    public void onCreate() {
        System.out.println("onCreate invoke");
        super.onCreate();
//        handler=new Handler(Looper.getMainLooper());
//        initClient();
    }

    /**
     * 每次通过startService()方法启动Service时都会被回调。
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("onStartCommand invoke");
//        if(connectFlag) {
//            handler.post(new Runnable() {
//                @Override
//                public void run() {
//                    Toast.makeText(getApplicationContext(), R.string.connect_socket_fail, Toast.LENGTH_SHORT).show();
//                }
//            });
//        }
        handler=new Handler(Looper.getMainLooper());
        initClient();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 服务销毁时的回调
     */
    @Override
    public void onDestroy() {
        System.out.println("onDestroy invoke");
        super.onDestroy();
    }


    private void initClient() {
        client = new Client();
        Network.register(client);
        QuerySQLEntity.register(client);
//        WifiLIstAndVoices.register(client);
        client.start();
        sharedPreferences = getSharedPreferences("ip", MODE_PRIVATE);
        final String firstIpvalue = sharedPreferences.getString("FirstIpAddress", "1");
        LogUtil.d(TAG,"ip=="+firstIpvalue);
        new Thread("Connect") {
            @Override
            public void run() {
                try {
                    client.connect(5000, firstIpvalue, 54555, 54777);
                    connectFlag=false;
                } catch (IOException ex) {
                    ex.printStackTrace();
                    LogUtil.e(TAG, ex.toString());
                    connectFlag=true;
                    //在service里面显示Toast
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), R.string.connect_socket_fail, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }.start();

        client.addListener(new Listener() {
            @Override
            public void received(Connection connection, Object object) {
                if (object instanceof Network.SomeResponse) {
                    Network.SomeResponse response = (Network.SomeResponse) object;
                    LogUtil.i(TAG,"response.type=="+response.type + response.toString());
                    switch (response.type){
                        case 5:
                            if (onReceiveServiceListener != null) {
                                PicRegistEntity pre = new PicRegistEntity(response.type,response.isRegist,"");
                                onReceiveServiceListener.getRebackType(pre);
                            }
                            break;
                        case 0:
                        case 1:
                            if (onReceiveServiceListener != null) {
                                PicRegistEntity pre = new PicRegistEntity(response.type,response.isRegist,"");
                                onReceiveServiceListener.getRebackType(pre);
                            }
                            break;
                        case 2:
                            LogUtil.i(TAG,"客户端接收的 picBit=="+ Arrays.toString(response.picBit));
                            final byte[] typeBit=response.picBit;
                            int sendNum=response.sendNum;
                            int cerrentNum=response.cerrentNum;
                            int byteLen=response.picBitLen;
                            long id=response.id;
                            int dataSize=response.dataSize;
                            LogUtil.d(TAG,sendNum+"查询的图片  客户端接收的 typeBit=="+typeBit.length+",,"+ Arrays.toString(typeBit)+"sendNum=="+sendNum+"cerrentNum=="+cerrentNum);
                            if (sendNum == 1) {
                                if (onReceiveServiceListener != null) {
                                    onReceiveServiceListener.getRebackPicByte(response.picBit,id,dataSize);
                                }
                            } else {
                                if (cerrentNum == 0) {
                                    oneByte=new byte[byteLen];
                                    System.arraycopy(typeBit, 0, oneByte, 0, typeBit.length);
                                    LogUtil.d(TAG,"查询的图片  服务端接收的 第一次收到的=="+Arrays.toString(oneByte));
                                }else{
                                    System.arraycopy(typeBit, 0, oneByte, cerrentNum*40000, typeBit.length);
                                    if(cerrentNum+1==sendNum){
                                        LogUtil.d(TAG,"查询的图片  服务端接收的最后 oneByte[]=="+oneByte.length+",,"+ Arrays.toString(oneByte));
                                        if (onReceiveServiceListener != null) {
                                            onReceiveServiceListener.getRebackPicByte(oneByte,id,dataSize);
                                        }
                                    }
                                }
                            }
                            break;
                        case 4:
                            //画框参数回调
                            if (onReceiveServiceListener != null) {
                                if(response.isComplete==0) {
                                    LogUtil.i(TAG,"画框参数 name=="+response.name+",,x=="+response.faceX
                                            +",,y=="+response.faceY+",,w=="+response.faceWidth+",,h=="+response.faceHeight+",,"+response.isComplete);
                                    onReceiveServiceListener.getInfoFaceData(response.name, response.faceX, response.faceY
                                            , response.faceWidth, response.faceHeight);
                                    LogUtil.i(TAG,"画框参数 name==完毕");
                                }else if(response.isComplete==1) {
                                    LogUtil.i(TAG,"画框清屏");
                                    onReceiveServiceListener.getIsClear();
                                }
                            }else
                                {
                                Log.w(TAG,"onReceiveServiceListener NULL");
                            }
                            break;
                    }
                }
                else if(object instanceof QuerySQLEntity.ResponseQuery){
                    QuerySQLEntity.ResponseQuery responseQuery = (QuerySQLEntity.ResponseQuery)object;
                    Log.i(TAG ,"@@WP:" + responseQuery.type + ";;" + responseQuery.name + responseQuery.isValid);
                    switch (responseQuery.type){

                        case 10://查询数据库，是否已经注册
                            PicRegistEntity picRegistEntity = new PicRegistEntity(10,responseQuery.isValid,"");
//                            if(responseQuery.isValid){
//                                if (onReceiveServiceListener != null) {
//                                    onReceiveServiceListener.getRebackType(101);//检索数据库成功
//                                }
//                            }else{
//                                if (onReceiveServiceListener != null) {
//                                    onReceiveServiceListener.getRebackType(100);//检索数据库失败
//                                }
//                            }
//                            InfoData infoData1 = infoData.queryData(requestQuery.name);
//                            if(infoData1 != null){
//                                responseQuery.type = 10;
//                                responseQuery.isValid = true;
//                                responseQuery.name =infoData1.getName();
//                            }else{
//                                responseQuery.type = 10;
//                                responseQuery.isValid = false;
//                                responseQuery.name = null;
//                            }
//                            connection.sendTCP(responseQuery);//返回数据库查询的结果
                                if (onReceiveServiceListener != null) {
                                    onReceiveServiceListener.getRebackType(picRegistEntity);//检索数据库失败
                                }
                            break;
                        case 12:
//接收AIKI来完成的
                            //bean转成json
                            Log.i(TAG, "sensers:" + responseQuery.toString());
                            if(responseQuery.frame.equals("1013")){//更新接口回调

                            }
                            if (onReceiveServiceListener != null) {
                                onReceiveServiceListener.getSensorParam(responseQuery);
                            }
//                    client.sendTCP(new Gson().toJson(response));
                            break;
                    }
                }
//                else if(object instanceof WifiLIstAndVoices.Response){
//                    //接收AIKI来完成的
//                    WifiLIstAndVoices.Response response = (WifiLIstAndVoices.Response)object;
//                    //bean转成json
//                    Log.i(TAG, "sensers:" + response.toString());
//                    if(response.frame.equals("1013")){//更新接口回调
//                        if (onReceiveServiceListener != null) {
//                            onReceiveServiceListener.getSensorParam(response);
//                        }
//                    }
////                    client.sendTCP(new Gson().toJson(response));
//                }
            }
            @Override
            public void connected(Connection connection) {
                ClientUtils.connectFlag = true;
//                Network.SomeRequest request = new Network.SomeRequest();
//                request.text = "Here is the request";
//                Log.d("yuecn","客户端连接成功");
//                client.sendTCP(request);
                //连接成功
                Log.i(TAG,"@@WP connected");
                Intent intent;
                if(RobotApplication.TEST){
                    intent=new Intent(getBaseContext(), ControlActivity.class);
                }else{
                    intent=new Intent(getBaseContext(), LoginActivity.class);
//                    intent=new Intent(getBaseContext(), ControlActivity.class);
                }

//                startActivity(intent);
//                Intent intent = new Intent(getBaseContext(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getApplication().startActivity(intent);
            }

            @Override
            public void disconnected(Connection connection) {
                super.disconnected(connection);
                ClientUtils.connectFlag = false;
                //断开连接后，尝试重连
                initClient();
//                sharedPreferences = getSharedPreferences("ip", MODE_PRIVATE);
//                final String firstIpvalue = sharedPreferences.getString("FirstIpAddress", "1");
//                LogUtil.d(TAG,"重连 ip=="+firstIpvalue);
//                new Thread("Connect") {
//                    public void run() {
//                        try {
//                            client.connect(5000, firstIpvalue, 54555, 54777);
//                        } catch (IOException ex) {
//                            ex.printStackTrace();
//                            LogUtil.e(TAG, ex.toString());
//                        }
//                    }
//                }.start();
            }
        });
    }


    public interface OnReceiveServiceListener
    {
        //控制小车和发送图片的监听返回
        void getRebackType(Object obj);
//        void getRebackType(int value);
        //查询图片的返回
        void getRebackPicByte(byte[] pisByte,long id,int dataSize);
        //人脸画框的回调
        void getInfoFaceData(String name,int x,int y,int w,int h);
        //清屏的回调
        void getIsClear();
        //传感器参数的回调
        void getSensorParam(Object obj);
    }

    public static OnReceiveServiceListener onReceiveServiceListener;

    public static void setOnPackageRemoveListener(OnReceiveServiceListener receiveServiceListener) {
        onReceiveServiceListener = receiveServiceListener;
    }
}
